<template>
	<view style="position: absolute;left: 100vw;top: 0;transform: translateY(-100%); visibility: hidden;">
		<canvas style="width: 415px;" canvas-type="2d" :style="{height:height+'px'}" canvas-id="firstCanvas"
			id="firstCanvas"></canvas>
	</view>
</template>

<script>
	import BASEURL from "@/config/utils.js"
	var app = getApp();
	export default {
		props: ["user", "time"],
		name: "billCanvas",
		mounted: function(e) {
			uni.$on("tempFilePath1", (data) => {
				this.signUrl = data || '';
			})
		},

		// destroyed() {
		// 	uni.$off('tempFilePath');
		// },
		methods: {
			draw() {
				let that = this
				return new Promise((resolve, reject) => {
					that.resolve = resolve
					that.reject = reject
					//记录当前y轴
					let x = 20
					let y = 0
					var context = uni.createCanvasContext('firstCanvas', that)
					context.fillStyle = "#FFFFFF";
					context.fillRect(0, 0, 415, that.height);
					context.fillStyle = "#000000";
					//产品数据
					let ShipmentList = that.$store.state.ShipmentList
					let ShipmentNumCount = 0
					let ShipmentPriceCount = 0
					//退货产品
					let returnList = that.$store.state.returnList
					let returnNumCount = 0
					let returnPriceCount = 0
					//用户信息
					let userInfo = app.globalData.userInfo;
					//清空画布
					context.setTextAlign('center')
					context.setFontSize(40)
					context.fillText(`${userInfo.mchCompany}-销售单`, 207, y += 100)
					context.setTextAlign('left')
					context.setFontSize(16)
					context.fillText(`客户:${that.user}`, x, y += 30)
					context.fillText(
						`下单时间:${that.time?that.time:uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')}`, x,
						y += 20)
					let totaAmountY = y += 20
					context.beginPath()
					if (ShipmentList.length > 0) {
						context.moveTo(x, y += 20);
						context.lineTo(375, y);
						//表头
						context.fillText('出货货号', x, y += 20)
						context.fillText('单价', 120, y)
						context.fillText('数量', 210, y)
						context.fillText('金额', 300, y)
						context.moveTo(x, y += 20);
						context.lineTo(375, y);
						//开始循环
						for (let item of ShipmentList) {
							context.fillText(item.proId, x, y += 20)
							context.fillText(item.realPrice, 120, y)
							context.fillText(item.orderNum, 210, y)
							ShipmentNumCount += item.orderNum;
							var orderAmout = Math.floor(item.realPrice * item.orderNum * 100) / 100;
							context.fillText(orderAmout, 300, y);
							ShipmentPriceCount += Math.floor(item.realPrice * item.orderNum * 100) / 100
							context.moveTo(x, y += 20);
							context.lineTo(375, y);
						}
						//结束循环
						context.fillText('小计', x, y += 20)
						context.fillText(ShipmentNumCount, 210, y)
						var orderAmout = Math.floor(ShipmentPriceCount * 100) / 100;
						context.fillText(orderAmout, 300, y)
					}

					// 退货产品
					if (returnList.length > 0) {
						context.moveTo(x, y += 40);
						// context.lineTo(375, y);
						context.moveTo(x, y += 40);
						context.lineTo(375, y);
						//表头
						context.fillText('退货货号', x, y += 20)
						context.fillText('单价', 120, y)
						context.fillText('数量', 210, y)
						context.fillText('金额', 300, y)
						context.moveTo(x, y += 20);
						context.lineTo(375, y);
						//开始循环
						for (let item of returnList) {
							context.fillText(item.proId, x, y += 20)
							context.fillText(item.realPrice, 120, y)
							context.fillText(item.orderNum, 210, y)
							returnNumCount += item.orderNum;
							var orderAmout = Math.floor(item.realPrice * item.orderNum * 100) / 100;
							context.fillText(orderAmout, 300, y)
							returnPriceCount += Math.floor(item.realPrice * item.orderNum * 100) / 100
							context.moveTo(x, y += 20);
							context.lineTo(375, y);
						}
						//结束循环
						context.fillText('小计', x, y += 20)
						context.fillText(returnNumCount, 210, y)
						var orderAmout = Math.floor(returnPriceCount * 100) / 100;
						context.fillText(orderAmout, 300, y)
						context.moveTo(x, y += 20);
						context.lineTo(375, y);
					}
					totaAmountY = y += 50
					var priceCount = Math.floor((ShipmentPriceCount - returnPriceCount) * 100) / 100;
					context.fillText(`总金额:${priceCount}`, x, totaAmountY);
					context.fillText(`地址:${userInfo.mchAddress || '-'}`, x, y += 80)
					context.fillText(`电话:${userInfo.mchTel || '-'}`, x, y += 20)
					context.fillText('客户签名', x, y += 30)
					if (that.signUrl) {
						// console.log(that.signUrl);
						context.drawImage(that.signUrl, x, y += 30, 375, 170)
					}
					that.height = y + 300
					context.stroke()
					that.$nextTick(() => {
						context.draw(false, that.dow)
					})
					// context.draw(false, () => {
					// 	console.log(123456);
					// })
				})



			},
			dow() {
				let that = this
				let token = uni.getStorageSync("token");
				uni.canvasToTempFilePath({
					fileType: "jpg",
					canvasId: 'firstCanvas',
					success: function(res) {
						console.log(res);
						// that.savePicture(res.tempFilePath)
						uni.uploadFile({
							url: BASEURL.baseURL + "/app/upload/uploadOss",
							filePath: res.tempFilePath,
							formData: {
								type: "detail"
							},
							header: {
								"X-Access-Token": token,
							},
							name: "file",
							success: (uploadFileRes) => {
								if (uploadFileRes.statusCode == 200) {
									console.log(456);
									that.resolve(JSON.parse(uploadFileRes.data).result)
								}
							},
						});


					},
					fail(e) {
						console.log(e);
					}

				}, that)

			},
			canvasIdErrorCallback: function(e) {
				console.error(e.detail.errMsg)
			},
			savePicture(base64) {
				var arr = base64.split(',');
				var bytes = atob(arr[1]);
				let ab = new ArrayBuffer(bytes.length);
				let ia = new Uint8Array(ab);
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				var blob = new Blob([ab], {
					type: 'application/octet-stream'
				});
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = new Date().valueOf() + ".png";
				var e = document.createEvent('MouseEvents');
				e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				a.dispatchEvent(e);
				URL.revokeObjectURL(url);
			},
			canvasInfo(signUrl) {
				uni.canvasGetImageData({
					canvasId: firstCanvas,
					x: 0,
					y: 0,
					width: 100,
					height: 100,
					success: function(res) {
						console.log("获取画布数据成功");
						console.log(res, 1);
						this.canvasOut = res
						// command.setBitmap(0, 0, 0, res);
						// command.setPrint(1);
						// that.prepareSend(command.getData()); //发送数据
					},
					complete: function(res) {
						console.log("finish");
					},
					fail: function(res) {
						console.log(res);
						uni.showToast({
							title: '获取画布数据失败',
							icon: 'none'
						});
					}
				});
			}
		},
		data() {
			return {
				signUrl: "",
				height: 2000,
				resolve: null,
				reject: null,
				canvasOut: {}
			};
		}
	}
</script>

<style lang="scss">

</style>